//
//  CalenderViewController.swift
//  MoodDiary
//
//  Created by MoodDiary on 2020/11/27.
//

import UIKit
import MJExtension
import SVProgressHUD

class CalenderViewController: UIViewController {
    
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var resetMonthBtn: UIButton!
    
    var titleBtn: UIButton?
    
    var hisDic: [String: [String: [[String: Any]]]]?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        resetMonthBtn.layer.borderWidth = 1.0
        resetMonthBtn.layer.borderColor = UIColor.lightGray.cgColor
        resetMonthBtn.layer.cornerRadius = 18.0
        resetMonthBtn.isHidden = true
        resetMonthBtn.addTarget(self, action: #selector(resetTapGesture), for: .touchUpInside)
        
        titleBtn = UIButton(type: .custom)
        titleBtn?.bounds = CGRect(x: 0, y: 0, width: 200.0, height: 30.0)
        titleBtn?.setTitle(NSString.currentYearAndMonth(), for: .normal)
        titleBtn?.setImage(UIImage(named: "向下"), for: .normal)
        titleBtn?.setTitleColor(.black, for: .normal)
        titleBtn?.titleLabel?.font = .systemFont(ofSize: 17.0, weight: .medium)
        titleBtn?.titleEdgeInsets = UIEdgeInsets(top: 0, left: -30.0, bottom: 0, right: 0)
        titleBtn?.imageEdgeInsets = UIEdgeInsets(top: 0, left: 130.0, bottom: 0, right: 0)
        titleBtn?.addTarget(self, action: #selector(titleAction), for: .touchUpInside)
        navigationItem.titleView = titleBtn
        
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(UINib(nibName: "CalenderCollectionViewCell", bundle: .main), forCellWithReuseIdentifier: "CalenderCollectionViewCell")
        collectionView.register(UINib(nibName: "CalenderHeaderView", bundle: .main), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "CalenderHeaderView")
        collectionView.register(UINib(nibName: "CalenderFooterView", bundle: .main), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "CalenderFooterView")
        
        DispatchQueue.main.async {
            let currentMonth = Int(NSString.currentMonth())
            self.collectionView.scrollToItem(at: IndexPath(row: 0, section: (currentMonth ?? 1) - 1), at: .top, animated: false)
        }
        
        NotificationCenter.default.rac_addObserver(forName: "createSucceed", object: nil)?.subscribeNext({ [weak self] (_) in
            self?.loadData()
        })
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "分享")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(shareAction))
        
        
        NotificationCenter.default.rac_addObserver(forName: "editDiaryCompleted", object: nil)?.subscribeNext({ [weak self] (_) in
            self?.loadData()
        })
    }
    
    @objc func resetTapGesture() {
        guard let currentMonth = Int(NSString.currentMonth()) else {
            return
        }
        
        let selectYear = NSString.currentYear()
        let selectMonth = NSString.currentMonth()
        
        if selectYear != (self.titleBtn?.currentTitle as NSString?)?.substring(to: 4) ?? "" {
            self.loadData()
        }
        
        self.titleBtn?.setTitle(selectYear + "-" + selectMonth, for: .normal)
        
        DispatchQueue.main.async { [weak self] in
            self?.collectionView.contentOffset = CGPoint(x: 0, y: (self?.collectionView.height)! * CGFloat(Int(selectMonth)!-1))
        }
        
//        let selectYear = (self.titleBtn?.currentTitle as NSString?)?.substring(to: 4) ?? ""
//        self.titleBtn?.setTitle(selectYear + "-" + "\(currentMonth)", for: .normal)
//        let scrollOffsetY = collectionView.height*CGFloat(currentMonth - 1)
//        collectionView.setContentOffset(CGPoint(x: 0, y: scrollOffsetY), animated: true)
        resetMonthBtn.isHidden = true
    }
    
    @objc func shareAction() {
        let vc = ShareViewController()
        vc.img = navigationController?.view?.captureImage
        vc.type = .diary
        vc.delegate = self
        let nav = MainNavigationController(rootViewController: vc)
        nav.modalTransitionStyle = .crossDissolve
        nav.modalPresentationStyle = .overCurrentContext
        UIApplication.shared.keyWindow?.rootViewController?.present(nav, animated: true, completion: nil)
        
        // 友盟事件统计
    }
    
    
    // 友盟页面统计
    override func viewWillAppear(_ animated: Bool)
    {
        super.viewWillAppear(animated)
        loadData()
        MobClick.beginLogPageView("心情日历")
        MobClick.event("pages_num", attributes: ["XinQingRiLi":"进入心情日历"])
    }
    
    override func viewWillDisappear(_ animated: Bool)
    {
        super.viewWillDisappear(animated)
        MobClick.endLogPageView("心情日历")
        MobClick.event("pages_num", attributes: ["XinQingRiLi":"离开心情日历"])
    }
    
    
    func loadData() {
        
        DispatchQueue.main.async { [weak self] in
            
            guard let self = self else { return }
            
            let selectYear = (self.titleBtn?.currentTitle as NSString?)?.substring(to: 4) ?? ""
            
            self.hisDic = [String: [String: [[String: Any]]]]()
            
            let fileManager = FileManager.default
            let docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as String
            let folderPath = docPath + "/" + selectYear + "/"
            
            guard fileManager.fileExists(atPath: folderPath) == true else {
                self.collectionView.reloadData()
                return
            }
            
            do {
                let fileNames: [String] = try fileManager.contentsOfDirectory(atPath: folderPath)

                for fileName: String in fileNames {
                  
                    let searchFolderPath = docPath + "/" + selectYear
                    let filePath = (searchFolderPath as NSString).appendingPathComponent(fileName)
                    guard fileManager.fileExists(atPath: filePath) == true else {
                        self.collectionView.reloadData()
                        return
                    }
                    
                    let monthDic = NSDictionary(contentsOfFile: filePath) as? [String : [[String : Any]]]
                    self.hisDic?[fileName] = monthDic
                    print("loadData hisDic == \(monthDic)")
                }
            } catch {
                print(error)
            }
            
            self.collectionView.reloadData()
            
        }
    }
    
}

extension CalenderViewController {
    
    @objc func titleAction() {
        
        let pickerView = UIPickerView(frame: CGRect(x: 35.0, y: 70.0, width: 200.0, height: 240.0))
        pickerView.delegate = self
        pickerView.dataSource = self
        
        DispatchQueue.main.async {
            
            let cYear = (self.titleBtn?.currentTitle as NSString?)?.substring(to: 4) ?? "1"
            let cYearInt: Int = cYear == NSString.currentYear() ? 0 : 1
            
            let cMonth = (self.titleBtn?.currentTitle as NSString?)?.substring(from: 5) ?? "1"
            let cMonthInt: Int = Int(cMonth) ?? 1
            
            pickerView.selectRow(cYearInt, inComponent: 0, animated: false)
            pickerView.selectRow(cMonthInt - 1, inComponent: 1, animated: false)
        }
        
        let alertC = UIAlertController(title: "提示", message: "请选择时间\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", preferredStyle: .alert)
        alertC.view.addSubview(pickerView)
        alertC.addAction(UIAlertAction(title: "确定", style: .default, handler: { [weak self] (_) in
            let selectIndex0 = pickerView.selectedRow(inComponent: 0)
            let selectIndex1 = pickerView.selectedRow(inComponent: 1)
            
            if selectIndex0 == 0 && selectIndex1 + 1 > Int(NSString.currentMonth()) ?? 0 {
                SVProgressHUD.showError(withStatus: "不能选择今天之后的日期")
                SVProgressHUD.dismiss(withDelay: 2.0)
                return
            }
            
            let selectYear = selectIndex0 == 0 ? NSString.currentYear() : "\((Int(NSString.currentYear()) ?? 1) - 1)"
            let selectMonth = String(format: "%02d", selectIndex1 + 1)
            
            if selectYear != (self?.titleBtn?.currentTitle as NSString?)?.substring(to: 4) ?? "" {
                self?.loadData()
            }
            
            self?.titleBtn?.setTitle(selectYear + "-" + selectMonth, for: .normal)
            
            if selectYear == NSString.currentYear() && selectMonth == NSString.currentMonth() {
                // 当月
                self?.resetMonthBtn?.isHidden = true
            } else {
                self?.resetMonthBtn?.isHidden = false
            }
            
            DispatchQueue.main.async { [weak self] in
                self?.collectionView.contentOffset = CGPoint(x: 0, y: (self?.collectionView.height)! * CGFloat(selectIndex1))
            }
        }))
        alertC.addAction(UIAlertAction(title: "取消", style: .destructive, handler: { (_) in
            
        }))
        present(alertC, animated: true, completion: nil)
        
    }
    
}

extension CalenderViewController: UIPickerViewDelegate, UIPickerViewDataSource {
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int { 2 }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if component == 0 { return 2 }
        return 12
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if component == 0 {
            let yearStr = NSString.currentYear()
            let yearInt = Int(yearStr)
            if row == 1 {
                return "\((yearInt ?? 1) - 1)年"
            }
            return "\(yearInt ?? 0)年"
        }
        return String(format: "%02d月", row + 1)
        
    }
}

extension CalenderViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let page: Int = Int(scrollView.contentOffset.y / scrollView.height)
        
        let selectYear = (titleBtn?.currentTitle as NSString?)?.substring(to: 4) ?? ""
        
        titleBtn?.setTitle(selectYear + "-" + String(format: "%02d", page + 1), for: .normal)
        
        // 非当月增加回到当月按钮
        if selectYear == NSString.currentYear() && Int(NSString.currentMonth()) == page + 1  {
            // 当月
            resetMonthBtn.isHidden = true
        } else {
            resetMonthBtn.isHidden = false
        }
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        
        let selectYear = (titleBtn?.currentTitle as NSString?)?.substring(to: 4)
        if selectYear != NSString.currentYear() {
            return 12
        }
        return Int(NSString.currentMonth()) ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let selectYear = Int((titleBtn?.currentTitle as NSString?)?.substring(to: 4) ?? "0") ?? 0
        
        switch section + 1 {
        case 1, 3, 5, 7, 8, 10, 12: return 31
        case 2:
            if (selectYear % 100 == 0 && selectYear % 400 == 0) || (selectYear % 100 != 0 && selectYear % 4 == 0) { return 29 } else { return 28 }
        default: return 30
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            let headrView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "CalenderHeaderView", for: indexPath)
            return headrView
        }
        let footerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "CalenderFooterView", for: indexPath)
        return footerView
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: collectionView.width, height: 60.0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        
        let currentYear = Int(NSString.currentYear()) ?? 0
        
        var count = 30
        
        switch section + 1 {
        case 1, 3, 5, 7, 8, 10, 12: count = 31
        case 2:
            if (currentYear % 100 == 0 && currentYear % 400 == 0) || (currentYear % 100 != 0 && currentYear % 4 == 0) { count = 29 } else { count = 28 }
        default: count = 30
        }
        
        let margin = 25.0
        let itemLength = (Double(collectionView.width) - margin * 4.0) / 5.0 - 1.0
        let lines = count / 5 + (count % 5 == 0 ? 0 : 1)
        let height = CGFloat(lines) * CGFloat(margin + itemLength) - CGFloat(margin) + 60.0
        
        return CGSize(width: collectionView.width, height: collectionView.height - height)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        let margin = 25.0
        let itemLength = (Double(collectionView.width) - margin * 4.0) / 5.0 - 1.0
        
        return CGSize(width: itemLength, height: itemLength)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { 25.0 }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { 25.0 }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: CalenderCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CalenderCollectionViewCell", for: indexPath) as! CalenderCollectionViewCell
        cell.delegate = self
        cell.currentIndexPath = indexPath
        
        let monthDic = self.hisDic?[String(format: "%02d.plist", indexPath.section + 1)]
        let dayStr = String(format: "%02d", indexPath.row + 1)
        let dayArray = monthDic?[dayStr]
        
        if dayArray != nil && (dayArray?.count ?? 0) > 0 {
            guard let data = try? JSONSerialization.data(withJSONObject: dayArray ?? [], options: JSONSerialization.WritingOptions.init()) else { return cell }
            let models = try? JSONDecoder().decode([DiaryModel].self, from: data)
            cell.dayArray = models
        } else {
            cell.dayArray = nil
        }
        
        let selectYear = (titleBtn?.currentTitle as NSString?)?.substring(to: 4)
        if selectYear != NSString.currentYear() {
            cell.label.text = "\(indexPath.row + 1)"
        } else if Int(NSString.currentMonth()) == indexPath.section + 1 && Int(NSString.currentDay()) == indexPath.row + 1 {
            cell.label.text = "今天"
        } else {
            cell.label.text = "\(indexPath.row + 1)"
        }
        
        if selectYear != NSString.currentYear() {
            cell.imgV.image = UIImage(named: "已过")
            cell.label.textColor = .black
        } else if Int(NSString.currentMonth()) == indexPath.section + 1 && (Int(NSString.currentDay()) ?? 1) < indexPath.row + 1 {
            cell.imgV.image = UIImage(named: "未到")
            cell.label.textColor = UIColor.hexColor(hex: "E1E1E1")
        } else {
            cell.imgV.image = UIImage(named: "已过")
            cell.label.textColor = .black
        }
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print(indexPath)
        
        let selectYear = (titleBtn?.currentTitle as NSString?)?.substring(to: 4)
        if selectYear == NSString.currentYear() && Int(NSString.currentMonth()) == indexPath.section + 1 && (Int(NSString.currentDay()) ?? 1) < indexPath.row + 1 {
            print("这天还没到")
        } else {
            
            let yearStr = (self.titleBtn?.currentTitle as NSString?)?.substring(to: 4) ?? ""
            var diaryModel = DiaryModel()
            if Int(NSString.currentMonth()) == indexPath.section + 1 && Int(NSString.currentDay()) == indexPath.row + 1 && NSString.currentYear() == yearStr {
                let vc = AddWeatherViewController()
                
                let nav = MainNavigationController(rootViewController: vc)
                nav.modalPresentationStyle = .overCurrentContext
                UIApplication.shared.keyWindow?.rootViewController?.present(nav, animated: true, completion: nil)
            } else {
                
                var timeStr = (titleBtn?.currentTitle ?? (NSString.currentYear() + NSString.currentMonth())) + "-" + "\(indexPath.row + 1)"
                timeStr += " "
                timeStr += NSString.getHourAndMinute(NSString.currentTimeStamp())
                diaryModel.timeStampStr = NSString.convertTime(toTimeStamp: timeStr)
                print("timeStr === \(timeStr)")
                
                // 默认晴天
                diaryModel.weatherStr = "晴天"
                
                let vc = AddMoodViewController()
                vc.dayStr = "这天"
                vc.diaryModel = diaryModel
                
                let nav = MainNavigationController(rootViewController: vc)
                nav.modalPresentationStyle = .overCurrentContext
                UIApplication.shared.keyWindow?.rootViewController?.present(nav, animated: true, completion: nil)
            }

        }
        
    }
    
}

extension CalenderViewController: CalenderCollectionViewCellDelegate {
    func calenderCollectionViewCellSelect(select: IndexPath?) {
        guard let select = select else { return }
        let monthDic = self.hisDic?[String(format: "%02d.plist", select.section + 1)]
        let dayStr = String(format: "%02d", select.row + 1)
        let dayArray = monthDic?[dayStr]
        if dayArray != nil && (dayArray?.count ?? 0) > 0 {
            if let monthDicNotNil = monthDic {
                let vc = DiaryForDayController()
                vc.monthDic = monthDicNotNil
                vc.mYear = (self.titleBtn?.currentTitle as NSString?)?.substring(to: 4) ?? ""
                vc.mMonth = "\(select.section + 1)"
                vc.mDay = "\(select.row + 1)"
                vc.hisDic = hisDic ?? [:]
                let nav = MainNavigationController(rootViewController: vc)
                nav.modalPresentationStyle = .overCurrentContext
                UIApplication.shared.keyWindow?.rootViewController?.present(nav, animated: true, completion: nil)
            } else {
                // 没有日记
                
            }
            
            
            
//            //有 直接跳转心情
//
//            var diaryModel = DiaryModel()
//
//            let vc = AddMoodViewController()
//
//            if Int(NSString.currentMonth()) == select.section + 1 && Int(NSString.currentDay()) == select.row + 1 {
//                print(1)
//                diaryModel.timeStampStr = NSString.currentTimeStamp()
//                vc.dayStr = "今天"
//            } else {
//                var timeStr = (titleBtn?.currentTitle ?? (NSString.currentYear() + NSString.currentMonth())) + "-" + "\(select.row + 1)"
//                timeStr += " "
//                timeStr += NSString.getHourAndMinute(NSString.currentTimeStamp())
//                diaryModel.timeStampStr = NSString.convertTime(toTimeStamp: timeStr)
//                vc.dayStr = "这天"
//            }
//
//            diaryModel.weatherStr = ""
//
//            vc.diaryModel = diaryModel
//
//            let nav = MainNavigationController(rootViewController: vc)
//            present(nav, animated: true, completion: nil)
            
        } else {
//            //没有 跳转天气
//            let vc = AddWeatherViewController.init()
//            let nav = MainNavigationController.init(rootViewController: vc)
//            nav.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
//            nav.modalTransitionStyle = UIModalTransitionStyle.coverVertical
//            self.present(nav, animated: true, completion: nil)
        }
    }
}

extension CalenderViewController: ShareViewControllerDelegate, AlertViewControllerDelegate {
    func shareWeChatDone(img: UIImage) {
        let vc = UIActivityViewController(activityItems: [img], applicationActivities: nil)
        present(vc, animated: true, completion: nil)
    }
    
    func shareWeiboDone(img: UIImage) {
        let vc = UIActivityViewController(activityItems: [img], applicationActivities: nil)
        present(vc, animated: true, completion: nil)
    }
    
//    func showAlertController(fromVC: UIViewController = (UIApplication.shared.keyWindow?.rootViewController)!, title: String) {
//        let alertC = AlertViewController()
//        alertC.alertTitle = title
//        alertC.delegate = self
//        alertC.modalTransitionStyle = .crossDissolve
//        alertC.modalPresentationStyle = .overCurrentContext
//        fromVC.present(alertC, animated: true, completion: nil)
//    }
    
    func alertViewControllerSureAction(alertTitle: String?) {
        guard let alertTitle = alertTitle else { return }
        
//        if alertTitle == "保存图片成功, 是否跳转到微信？" {
//            UIApplication.shared.open(URL(string: "wechat://")!, options: [:], completionHandler: nil)
//        }
//        if alertTitle == "保存图片成功, 是否跳转到微博？" {
//            UIApplication.shared.open(URL(string: "weibo://")!, options: [:], completionHandler: nil)
//        }
        
        
    }
    
}
